import httplib
import json



def makeRequest(domin, url, extra_headers = None, params = {}):
	headers = {"Content-type": "application/x-www-form-urlencoded"}
	if extra_headers is not None:
		headers.update(extra_headers)
	
	conn = httplib.HTTPSConnection(domin)
	conn.request("POST", url, params, headers)
	response = conn.getresponse().read()
	conn.close()
	
	return response

def makeJSONRequest(domin, url, extra_headers = None, params = {}):
	response = makeRequest(domin, url, extra_headers, params)
	# Fix up bogus values returned by the API; sometimes floating-point
	# numbers with no fractional value are returned as 1. instead of 1.0, etc.
	response = response.replace(".,", ".0,")
	
	try:
		r = json.loads(response)
	except Exception as e:
		print "Error while attempting to parse JSON response: %s" % e
		print "Response: %r" % response
		raise e
	
	return r

def pair2graph(pairs):
	ret_g = {}
	for v in pairs:
		t1, t2 = v.split("_")
		if t1 not in ret_g:ret_g[t1] = []
		ret_g[t1].append(t2)
		if t2 not in ret_g:ret_g[t2] = []
		ret_g[t2].append(t1)
	return ret_g



class MarketGraph():
	_G = {}
	allpath = []
	_seq = []
	_got = set()
	def __init__(self,G):
		self._G = G
	def _dfs(self, head, what, dep):
		self._seq.append(what)
		if dep > 0:self._got.add(what)
		if dep > 0 and what == head:
			if dep > 2:self.allpath.append(self._seq[:])
			self._seq.pop()
			self._got.remove(what)
			return
		for i in self._G[what]:
			if i not in self._got:
				self._dfs(head, i,dep+1)
		if dep > 0:self._got.remove(what)
		self._seq.pop()
	def calPath(self, head):
		self._dfs(head, head, 0);
	



if __name__ == "__main__":
	gg = pair2graph(
		["btc_usd","btc_rur","btc_eur","ltc_btc",
		"ltc_usd","ltc_rur","usd_rur","eur_usd"])
	mk = MarketGraph(gg)
	mk.calPath("btc")
	mk.calPath("usd")

	print mk.allpath
	print makeJSONRequest("btc-e.com", "/api/2/btc_usd/depth")
	print makeJSONRequest("btc-e.com", "/api/2/usd_rur/depth")
